import React from 'react';
import {
  TouchableOpacity,
  View,
  Text,
  Animated,
} from 'react-native';

import BaseComponent from './BaseComponent';
import Config from '../../config';
import SizeUtils from '../../common/SizeUtils';

const ITEM_HEIGHT = 80;
const SAPCE = 40;

export default class CommonOptionView extends BaseComponent {
  constructor(props) {
    super(props);

    this._cancelData = {text:"取  消", onPress:this._hideView.bind(this)}
    this._totalHeight = this._getData().length * ITEM_HEIGHT + SAPCE;
    this.state.animateY = new Animated.Value(-this._totalHeight);
  }

  componentDidMount() {
    Animated.timing(
      this.state.animateY,
        {toValue: 0,
        duration: 500}
    ).start();
  }

  componentWillUnmount() {
    this.state.animateY.stopAnimation();
    this.setState({
      animateY:null,
    });
  }

  render() {
    let dataArr = this._getData();
    return(
      <View style={this.props.style}>
        <TouchableOpacity  activeOpacity={1} style={{width:SizeUtils.getWindowSize().width,
          height:SizeUtils.getWindowSize().height, backgroundColor:"#000000dd"}} onPress={this._hideView.bind(this)}>
          {dataArr.map((data, index) => {
            return this._renderItem(data, index)
          })}
        </TouchableOpacity>
      </View>
    )
  }

  _renderItem(data, index) {
    return(
      <TouchableOpacity key={index} style={{width:SizeUtils.getWindowSize().width,
        height:SizeUtils.translateDesignHeightToCode(ITEM_HEIGHT),
        position:"absolute", bottom:this._getBottom(index)}}
        onPress={data.onPress} >
        <Animated.View style={{bottom:this.state.animateY, backgroundColor:"#ffffff"}}>
          <TouchableOpacity style={{width:SizeUtils.getWindowSize().width,
            height:SizeUtils.translateDesignHeightToCode(ITEM_HEIGHT),
             flexDirection:"row", justifyContent:"center", alignItems:"center"}} onPress={() => this._onPressImte(data)}>
            <Text style={{textAlign:"center", fontSize:SizeUtils.translateFontSizeToCode(30)}}>
              {data.text}
            </Text>
          </TouchableOpacity>
        </Animated.View>
      </TouchableOpacity>
    )
  }

  _onPressImte(data) {
    data.onPress();
  }

  _getBottom(index) {
    let bottom = 0;
    if(index == 0) {
      bottom = 0;
    }
    else {
      bottom = ITEM_HEIGHT * index + SAPCE;//20为离cancel item 的距离
    }
    // bottom = bottom - ITEM_HEIGHT + 20;
    return SizeUtils.translateDesignHeightToCode(bottom);
  }

  _getData() {
    let dataArr = [this._cancelData];
    if(this.props.optionData != undefined) {
      dataArr = dataArr.concat(this.props.optionData);
    }
    return dataArr;
  }

  _hideView() {
    Animated.timing(
      this.state.animateY,
        {toValue: -this._totalHeight,
        duration: 300}
    ).start(this._hideAnimatedComplete.bind(this));
    // this._hideAnimatedComplete();
  }

  _hideAnimatedComplete() {
    this.props.onClose();
  }
}
